package cevent.source.cloudcenter.server.service;

import cevent.source.cloudcenter.server.domain.Category;
import cevent.source.cloudcenter.server.domain.CategoryExample;
import cevent.source.cloudcenter.server.dto.CategoryChildrenDto;
import cevent.source.cloudcenter.server.dto.CategoryDto;
import cevent.source.cloudcenter.server.dto.PageDto;
import cevent.source.cloudcenter.server.mapper.CategoryMapper;
import cevent.source.cloudcenter.server.mapper.commonMapper.CommonModuleMapper;
import cevent.source.cloudcenter.server.util.DuplicateUtil;
import cevent.source.cloudcenter.server.util.UUID8Util;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author cevent
 * @description 总分类表服务层
 */
@Service
public class CategoryService {
    private static final Logger LOG = LoggerFactory.getLogger(CategoryService.class);

    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private CommonModuleMapper commonModuleMapper;

    //1.无分页列表查询：dto获取domain参数
    public List<CategoryDto> categoryDtoList() {
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("uni_id asc");
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);
        List<CategoryDto> categoryDtoList = DuplicateUtil.copyList(categoryList, CategoryDto.class);
        return categoryDtoList;
    }

    //tree型结构输出list
    public List<CategoryChildrenDto> categoryTreeList() {
        //1.获取所有分类
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);
        List<CategoryChildrenDto> categoryChildrenList = DuplicateUtil.copyList(categoryList, CategoryChildrenDto.class);
        //2.组装tree型结构
        //2.1获取一级分类:过滤
        List<CategoryChildrenDto> level1 = categoryChildrenList.stream().filter((category) -> {
            return category.getParentId().equals("00000000");
            //递归设置子分类
        }).map((cat) -> {
            cat.setChildren(getCategoryChildren(cat, categoryChildrenList));
            return cat;
            //遍历结果排序
        }).sorted((cat1, cat2) -> {
            return (cat1.getSort() == null ? 0 : cat1.getSort()) - (cat2.getSort() == null ? 0 : cat2.getSort());
        }).collect(Collectors.toList());

        return level1;
    }

    //获取某一个分类的子分类，需要传入(current当前分类实体,all所有分类实体集合)，递归查询子分类
    private List<CategoryChildrenDto> getCategoryChildren(CategoryChildrenDto categoryChildrenDto, List<CategoryChildrenDto> categoryChildrenDtoList) {
        //1.过滤菜单
        List<CategoryChildrenDto> categoryChildren = categoryChildrenDtoList.stream().filter(category -> {
            //1.1父子分类判断
            return category.getParentId().equals(categoryChildrenDto.getUniId());
            //1.2递归查询，再次自调用获取子分类
        }).map((category) -> {
            category.setChildren(getCategoryChildren(category, categoryChildrenDtoList));
            return category;
            //1.3排序
        }).sorted((cat1, cat2) -> {
            //return cat1.getSort()-cat2.getSort();
            //避免空指针异常
            return (cat1.getSort() == null ? 0 : cat1.getSort()) - (cat2.getSort() == null ? 0 : cat2.getSort());
            //生成集合
        }).collect(Collectors.toList());
        return categoryChildren;
    }

    /*2.分页查询：pageDto保存数据
        list数据集合：listPageData
        当前页码：currentPage
        每页行数：size
        总计函数：totalSize
        前端可返回pageDto，无需返回值
     */
    public void getCategoryPageDtoList(PageDto pageDto) {
        //1.分页设置（前端传入当前页和每页行数params），起始页，每页行数size
        PageHelper.startPage(pageDto.getCurrentPage(), pageDto.getSize());

        CategoryExample categoryExample = new CategoryExample();

        categoryExample.setOrderByClause("sort asc");

        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);
        //2.将mapper查询结果复制到pageInfo
        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);
        //3.pageInfo计算处理处理=>后分页的总行数set到pageDto做记录
        pageDto.setTotalSize(pageInfo.getTotal());

        List<CategoryDto> categoryDtoList = new ArrayList<>();
        categoryList.stream().forEach(category -> {
            CategoryDto categoryDto = new CategoryDto();
            BeanUtils.copyProperties(category, categoryDto);
            categoryDtoList.add(categoryDto);
        });

        pageDto.setListPageData(categoryDtoList);

    }

    //3.新增、修改category，将传入的id转为category对象本身
    public void save(CategoryDto categoryDto) {
        Category category = DuplicateUtil.copy(categoryDto, Category.class);
        if (StringUtils.isEmpty(categoryDto.getUniId())) {
            this.insert(category);
        } else {
            this.update(category);
        }

    }

    //根据uniId更新moduleId
    public void saveModuleId(String moduleId, List<CategoryChildrenDto> categoryChildrenDtoList) {
        Category category = new Category();
        List<Category> categoryList = DuplicateUtil.copyList(categoryChildrenDtoList, Category.class);
        for (int i = 0; i < categoryList.size(); i++) {
            category = categoryList.get(i);
            //获取到每一个category的uniId
            category.setModuleId(moduleId);
            //传入每一个category对象进行更新操作
            categoryMapper.updateByPrimaryKeySelective(category);
        }
    }

    //4.删除模块
    public void delete(String uniId) {
        CategoryExample categoryExample = new CategoryExample();
        categoryMapper.deleteByPrimaryKey(uniId);
    }

    //5.向外暴露dto，不暴露实体类：插入数据
    private void insert(Category category) {
        category.setUniId(UUID8Util.getShortUUID());
        if (category.getParentId() == null) {
            category.setParentId("0");
        }
        if (category.getModuleId() == null) {
            category.setModuleId("0");
        }
        if (category.getLevel() == null) {
            category.setLevel(0);
        }

        categoryMapper.insert(category);
    }

    //6.更新模块
    private void update(Category category) {
        try {
            Date now = new Date();
            String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now);
            long time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date).getTime();
            int timeInt = (int) (time / 1000);

        } catch (ParseException e) {
            e.printStackTrace();
        }

        categoryMapper.updateByPrimaryKey(category);
    }

    //7.根据传入的id获取category
    public CategoryDto getCategoryInfo(String uniId) {

        Category category = categoryMapper.selectByPrimaryKey(uniId);
        CategoryDto categoryDto = DuplicateUtil.copy(category, CategoryDto.class);
        return categoryDto;
    }

    //8.批量更新节点level
    public List<Category> updateLevelByUniId(CategoryDto[] categoryDto) {
        //1.将传入的数组，转化为dtoList
        List<CategoryDto> categoryDtoList = Arrays.asList(categoryDto);
        //2.将dtoList复制到domainList
        List<Category> categoryList = DuplicateUtil.copyList(categoryDtoList, Category.class);
        //3.循环domainList
        for (int i = 0; i < categoryList.size(); i++) {
            //4.获取每一个category对象
            Category category = categoryList.get(i);
            //5.批量更新sql
            categoryMapper.updateByPrimaryKeySelective(category);
        }
        //boolean flag=commonModuleMapper.updateBatchDraggingById(categoryList);
        return categoryList;
    }

    //9.批量删除
    public int delBatchCategory(String[] uniIds) {
        CategoryExample categoryExample = new CategoryExample();
        //将String转化为list
        categoryExample.createCriteria().andUniIdIn(Arrays.asList(uniIds));
        //1.根据传入的数组删除
        int flag = categoryMapper.deleteByExample(categoryExample);
        return flag;
    }

    //10.根据ModuleCategory获取到的dtoList中的categoryUniIds获取categoryChildrenDtoList
    public List<CategoryDto> getCategoryChildrenList(String categoryId) {
        //预设封装categoryList
        List<CategoryDto> categoryDtoList = new ArrayList<>();
        LOG.info("传入的categoryId：", categoryId);
        //CategoryExample categoryExample = new CategoryExample();
        //LOG.info("asList转换：{}",Arrays.asList(categoryIds));
        Category category = categoryMapper.selectByPrimaryKey(categoryId);
        LOG.info("查询到的category对象：{}", category);
        if (!category.getParentId().equals("00000000")) {
            Category category1 = categoryMapper.selectByPrimaryKey(category.getParentId());
            LOG.info("第一层判断，非0000000，输出：{}", category1);
            if (!category1.getParentId().equals("00000000")) {
                Category category2 = categoryMapper.selectByPrimaryKey(category1.getParentId());
                LOG.info("第二层判断，非0000000，输出：{}", category2);
                if(!category2.getParentId().equals("00000000")){
                    Category category3 = categoryMapper.selectByPrimaryKey(category2.getParentId());
                    LOG.info("第三层判断，非0000000，输出：{}", category3);
                    categoryDtoList.add(DuplicateUtil.copy(category3,CategoryDto.class));
                    categoryDtoList.add(DuplicateUtil.copy(category2,CategoryDto.class));
                    categoryDtoList.add(DuplicateUtil.copy(category1,CategoryDto.class));
                    categoryDtoList.add(DuplicateUtil.copy(category,CategoryDto.class));
                }else{
                    categoryDtoList.add(DuplicateUtil.copy(category2,CategoryDto.class));
                    categoryDtoList.add(DuplicateUtil.copy(category1,CategoryDto.class));
                    categoryDtoList.add(DuplicateUtil.copy(category,CategoryDto.class));
                }
            }else{
                categoryDtoList.add(DuplicateUtil.copy(category1,CategoryDto.class));
                categoryDtoList.add(DuplicateUtil.copy(category,CategoryDto.class));
            }

        }else{
            categoryDtoList.add(DuplicateUtil.copy(category,CategoryDto.class));
        }

        //List<CategoryChildrenDto> categoryChildrenDtoList=DuplicateUtil.copyList();
        return categoryDtoList;
    }

    //递归获取父分类
    private List<Category> getParents(Category category, List<Category> categoryList) {
        return null;
    }
}
